package com.iconmaker.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.widget.LinearLayout;

import com.iconmaker.model.Conf;
import com.iconmaker.model.State;
import com.iconmaker.util.FileManager;

public class DataManager {
	public static void save(LinearLayout pixcelContainerView, String fileName) {
		Bitmap bitmap = null;
		
		try {
			String rootPath = Conf.rootPath + CanvasActivity.getContext().getPackageName();
			
			File file = new File(rootPath);
			if(!file.exists())
				file.mkdirs();
			
			file = new File(rootPath + "/" + fileName);
			if(!file.exists())
				file.createNewFile();
			
			bitmap = Bitmap.createBitmap(Conf.countOfColumnPixcel, Conf.countOfRowPixcel, Bitmap.Config.ARGB_8888);
			
			for(int i = 0; i < Conf.countOfRowPixcel; i++) {
				for(int j = 0; j < Conf.countOfColumnPixcel; j++) {
					bitmap.setPixel(i, j, State.canvasState[i][j]);
				}
			}
			
			bitmap.compress(CompressFormat.PNG, 100, new FileOutputStream(file));
			
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			if(bitmap != null)
				bitmap.recycle();
		}
		
	}
	
	public static void remove(String fileName) {
		String path = Conf.rootPath + GalleryActivity.getContext().getPackageName() + "/" + fileName;
		FileManager.getInstance().deleteFile(path);
	}
	
	public static String getDatte() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date();
		
		return dateFormat.format(date).toString();
	}
	
	public static void share() {
		Intent shareIntent = new Intent(Intent.ACTION_SEND);
		shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
		shareIntent.setType("image/*");
		
		Uri uri = Uri.fromFile(new File(Conf.rootPath + GalleryActivity.getContext().getPackageName() + "/" + State.loadImageName));
		shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
		
		CanvasActivity.getContext().startActivity(shareIntent);
	}
}
